package com.kmcsoft.core;

import com.kmcsoft.core.service.MasterService;
import com.kmcsoft.demography.entity.Address;
import com.kmcsoft.demography.entity.District;
import com.kmcsoft.demography.entity.Province;
import com.kmcsoft.demography.entity.Ward;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.zkoss.zk.ui.HtmlMacroComponent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zkplus.databind.AnnotateDataBinder;
import org.zkoss.zkplus.spring.SpringUtil;
import org.zkoss.zul.impl.InputElement;

/**
 *
 * @author phuocthai
 */
public class AddressMacro extends HtmlMacroComponent {

    private Address value;
    private AnnotateDataBinder binder;
    private InputElement selfComp;
    @Autowired
    private MasterService masterService;

    protected Logger log = LoggerFactory.getLogger(getClass()); 
    
    @Override
    public void afterCompose() {
        super.afterCompose();

        if (masterService == null) {
            masterService = (MasterService) SpringUtil.getBean("masterService");
        }

        selfComp.setAttribute("macroComposer", this);
        
        binder = new AnnotateDataBinder(this);
        this.setAttribute("binder", binder);
        this.setAttribute("addressComp", this);
        binder.setLoadOnSave(false);
        binder.loadAll();
    }
    
    public void onBindingSaveAddress(Event evt) {
        log.debug("Before bindingSave");
        if (value == null) {
            value = new Address();
        }
    }

    public void setDisabled(boolean b) {
        selfComp.setDisabled(b);
    }

    public boolean isDisabled() {
        return selfComp.isDisabled();
    }

    public Collection<Province> getProvinces() {
        if (value == null) {
            return null;
        }
        return masterService.getProvinces(value.getCountry());
    }

    public Collection<District> getDistricts() {
        if (value == null) {
            return null;
        }
        return masterService.getDistricts(value.getProvince());
    }

    public Collection<Ward> getWards() {
        if (value == null) {
            return null;
        }
        return masterService.getWards(value.getDistrict());
    }

    public Address getValue() {
        return value;
    }

    public void setValue(Address value) {
        this.value = value;
        log.debug("Setting address value: {}" + value);
    }
    
    public String getText() {
        if (value == null) return "";
        return value.toString();
    }
}
